package com.example.administrator.testxingpiao.ui.city;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.github.promeg.pinyinhelper.Pinyin;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/11.
 */
public class CityAsyncTask extends AsyncTask<Context,Void,List<City>>{

    private OnGetCityListListener mListenr;
    public interface OnGetCityListListener{

        void onGetCityList(List<City> result);
    }
    public CityAsyncTask(OnGetCityListListener listener){
        this.mListenr = listener;
    }

    @Override
    protected List<City> doInBackground(Context... params) {
        List<City> mList = new ArrayList<>();
        String json = getLocalJson(params[0]);
        JSONArray array = null;
        try {
            array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                JSONArray cityArray = array.getJSONObject(i).getJSONArray("city");
                for (int j = 0; j < cityArray.length(); j++) {
                    String name = cityArray.getJSONObject(j).getString("name");
                    City city = new City();
                    city.setCityName(name);
                    city.setCityPinyin(transformPinYin(name));
                    mList.add(city);
                }
            }
            Log.i("TAG","dobackground中：size=" + mList.size());
            return mList;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<City> cities) {
        Log.i("TAG","进入Post方法中！");
        super.onPostExecute(cities);
        Log.i("TAG","post中：size=" + cities.size());
        mListenr.onGetCityList(cities);
    }

    private String getLocalJson(Context context){
        String line;
        String json = "";
        InputStream is = context.getClass().getClassLoader().getResourceAsStream("assets/city.json");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                json += line.trim();
            }
            return json.trim();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String transformPinYin(String character) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < character.length(); i++) {
            buffer.append(Pinyin.toPinyin(character.charAt(i)));
        }
        return buffer.toString();
    }
}
